import { SwapRightOutlined, WarningTwoTone } from '@ant-design/icons';
import { ProCard } from '@ant-design/pro-components';
import { Badge, List, message, Tabs, Tag, Typography } from 'antd';
import React, { useState } from 'react';
import styles from './DetailMonitorArticleContent.less';

interface DetailMonitorArticleContentProps {
  name: string;
  content: string;
  errorWords: any[];
  keywords: string[];
  onRefurbish: () => void;
}

const DetailMonitorArticleContent: React.FC<DetailMonitorArticleContentProps> = ({
  name,
  content,
  errorWords,
  keywords,
  onRefurbish,
}) => {
  const [html, setHtmlValueState] = useState<string>(content);
  const [checks, setCheckState] = useState<MonitorArticleData.GreenTextInspectWords[]>(errorWords);
  const [tab, setTab] = useState('tab1');
  const visibleChecks = checks.filter((item) => item.inspectTypeEn !== 'punctuation');
  /**
   * 词 标记
   */
  const wordMark = (id: string) => {
    const original = html
      .replaceAll(
        `class="${styles['word-mark-error-highlight-major']}"`,
        `class="${styles['word-mark-error-major']}"`,
      )
      .replaceAll(
        `class="${styles['word-mark-error-highlight-critical']}"`,
        `class="${styles['word-mark-error-critical']}"`,
      )
      .replaceAll(
        `class="${styles['word-mark-error-highlight-blocker']}"`,
        `class="${styles['word-mark-error-blocker']}"`,
      )
      .replaceAll(
        `class="${styles['word-mark-right-highlight']}"`,
        `class="${styles['word-mark-right']}"`,
      );

    visibleChecks.forEach((item: MonitorhcData.GreenTextInspectWords) => {
      if (`word${item.id}` === id) {
        item.click = 1;

        let errorWord = '';
        let errorWordHighlight = '';

        const inspectTypeEn = item.inspectTypeEn;

        switch (inspectTypeEn) {
          case 'traditionalchinese': //繁简误用
          case 'variantchar': //异体字检查
          case 'transerror': //译文检查
          case 'terms': //不规范名词检查
          case 'keywords': //重点词检查
          case 'ADtime': //公元纪年错误
          case 'historytime': //历史纪年错误
          case 'branchtime': //干支纪年错误
          case 'placenameused': //地名检查（曾用名）
          case 'placenamematch': //地名检查（新旧地名不匹配）
          case 'placenamedivision': //地名检查（所属区 划错误）
          case 'placenamelevel': //地名检查（层级错误）
          case 'nonrecommender': //非推荐词
          case 'errorspace': //多余空格
            //一般
            errorWord = `id="word${item.id}" class="${styles['word-mark-error-major']}"`;
            errorWordHighlight = `id="word${item.id}" class="${styles['word-mark-error-highlight-major']}"`;
            break;
          case 'errorwords': //易错词检查
          case 'grammar': //语法检查
          case 'englishmodel': //英文检查
          case 'sentivewords': //敏感词检查
          case 'punctuation': //标点符号检查
          case 'semrepetition': //语义重复
            //严重
            errorWord = `id="word${item.id}" class="${styles['word-mark-error-critical']}"`;
            errorWordHighlight = `id="word${item.id}" class="${styles['word-mark-error-highlight-critical']}"`;
            break;
          case 'leadername': //领导人姓名检查
          case 'leadersort': //领导人排序检查
          case 'leadertitle': //领导人职务检查
          case 'politicalman': //提及政要
            //崩溃
            errorWord = `id="word${item.id}" class="${styles['word-mark-error-blocker']}"`;
            errorWordHighlight = `id="word${item.id}" class="${styles['word-mark-error-highlight-blocker']}"`;
            break;
        }

        console.log('=1===', errorWord);
        console.log('=2=====', errorWordHighlight);
        console.log('=3=====', original);
        console.log('=3=====', original.replace(errorWord, errorWordHighlight));

        setHtmlValueState(original.replace(errorWord, errorWordHighlight));
      } else {
        item.click = 0;
      }
    });

    setCheckState(checks);
  };

  return (
    <Tabs activeKey={tab} onChange={setTab}>
      <Tabs.TabPane tab="文章信息" key="tab1">
        <ProCard bordered>
          <Typography.Title level={3} style={{ textAlign: 'center' }}>
            {name ? name : '暂无标题'}
          </Typography.Title>
          <br />
          {html ? (
            <div
              className={styles['scroll-hidden']}
              style={{
                height: '550px', // 设置固定高度
                overflowY: 'scroll', // 启用垂直滚动
                whiteSpace: 'pre-line',
              }}
              dangerouslySetInnerHTML={{
                __html: `${html}`,
              }}
            />
          ) : (
            <>暂无文章内容</>
          )}
        </ProCard>
      </Tabs.TabPane>
      <Tabs.TabPane tab="错误信息" key="tab2">
        {visibleChecks.length > 0 ? (
          <ProCard bordered>
            <WarningTwoTone twoToneColor="red" /> 检测到疑似问题 {visibleChecks.length} 处
            <div
              style={{
                height: 615,
                overflowX: 'hidden',
                overflowY: 'scroll',
                marginTop: 10,
                scrollbarWidth: 'none',
                paddingLeft: 10,
                paddingRight: 10,
              }}
            >
              {visibleChecks.map((item, index) => {
                let ribbonColor = 'orange';
                if (item.repair == 1) {
                  ribbonColor = '#0DBC79';
                } else {
                  if (item.ignore == 1) {
                    ribbonColor = 'blue';
                  } else {
                    const inspectTypeEn = item.inspectTypeEn;
                    const inspectCategory = item.inspectCategory;
                    switch (inspectTypeEn) {
                      case 'traditionalchinese': //繁简误用
                      case 'variantchar': //异体字检查
                      case 'transerror': //译文检查
                      case 'terms': //不规范名词检查
                      case 'keywords': //重点词检查
                      case 'ADtime': //公元纪年错误
                      case 'historytime': //历史纪年错误
                      case 'branchtime': //干支纪年错误
                      case 'placenameused': //地名检查（曾用名）
                      case 'placenamematch': //地名检查（新旧地名不匹配）
                      case 'placenamedivision': //地名检查（所属区 划错误）
                      case 'placenamelevel': //地名检查（层级错误）
                      case 'nonrecommender': //非推荐词
                      case 'errorspace': //多余空格
                        //一般
                        ribbonColor = '#FFC300';
                        break;
                      case 'errorwords': //易错词检查
                      case 'grammar': //语法检查
                      case 'englishmodel': //英文检查
                      case 'sentivewords': //敏感词检查
                      case 'punctuation': //标点符号检查
                      case 'semrepetition': //语义重复
                        //严重
                        ribbonColor = 'orange';
                        break;
                      case 'leadername': //领导人姓名检查
                      case 'leadersort': //领导人排序检查
                      case 'leadertitle': //领导人职务检查
                      case 'politicalman': //提及政要
                        //崩溃
                        ribbonColor = '#C70039';
                        break;
                    }
                    if (inspectCategory === '错误') {
                      ribbonColor = 'red';
                    }
                  }
                }

                return (
                  <a
                    key={item.id}
                    id={`check${item.id}`}
                    href={`#word${item.id}`}
                    style={{ textDecoration: 'none', color: 'while', cursor: 'default' }}
                  >
                    <ProCard
                      hoverable
                      style={{
                        backgroundColor: item.click === 1 ? '#cff2ff' : '',
                        color: 'black',
                        marginTop: 10,
                        marginBottom: 10,
                        cursor: 'default',
                      }}
                      onClick={() => {
                        if (item.ignore != 1) {
                          wordMark(`word${item.id}`);
                        } else {
                          message.warning('已经忽略');
                        }
                        setTab('tab1');
                      }}
                    >
                      <Badge.Ribbon
                        text={index + 1}
                        placement="start"
                        style={{
                          marginTop: '-10px',
                        }}
                        color={ribbonColor}
                      >
                        <div
                          style={{
                            marginLeft: '35px',
                          }}
                        >
                          <Tag color={item.inspectCategory == '可疑' ? 'orange' : 'red'}>
                            {item.inspectCategory === '可疑' ? '核对' : item.inspectCategory}
                          </Tag>
                          {item.content}
                          {item.lookup && (
                            <>
                              <SwapRightOutlined /> {item.lookup}
                            </>
                          )}
                        </div>
                      </Badge.Ribbon>
                      <div
                        style={{
                          flex: 1,
                          marginTop: 16,
                          justifyContent: 'space-between',
                          display: 'flex',
                        }}
                      >
                        <div
                          style={{
                            display: 'inline',
                          }}
                        >
                          <div>原因：{item.content}</div>
                          <div>提示：{item.inspectType}</div>
                        </div>

                        <div
                          style={{
                            display: 'inline',
                          }}
                        ></div>
                      </div>
                    </ProCard>
                  </a>
                );
              })}
            </div>
          </ProCard>
        ) : (
          <ProCard bordered>暂无错误信息</ProCard>
        )}
      </Tabs.TabPane>
      <Tabs.TabPane tab="本地涉政" key="tab3">
        {keywords.length > 0 ? (
          <ProCard bordered>
            <WarningTwoTone twoToneColor="red" /> 检测到本地涉政关键字 {keywords.length} 处
            <List
              size="large"
              dataSource={keywords}
              renderItem={(item) => (
                <List.Item>
                  <List.Item.Meta title={item} />
                </List.Item>
              )}
            />
          </ProCard>
        ) : (
          <ProCard bordered>暂无本地涉政关键字</ProCard>
        )}
      </Tabs.TabPane>
    </Tabs>
  );
};

export default DetailMonitorArticleContent;
